<?php
class uploadproject extends controller{
	public $link;

	public function __construct($url){
		parent::__construct($url, true);
		$this->link = null;
	}

	public function check(){
		if($_SESSION["user"][5] < 2) $this->redirect("start", "Nincs jogosultsága ehhez a funkcióhoz!");
		if(!isset($this->url[1]) || empty($this->url[1])) $this->redirect("start", "A megadott azonosítójú projekt nem létezik!");
	}

	public function run(){
		$this->getLink();
		$this->uploadproject();
	}

	private function getLink(){
		$sql = "SELECT link FROM project WHERE id=".$this->url[1];
		$tmp = $this->database->fetchRow($sql);
		$this->link = $tmp[0][0];
	}

	private function uploadproject(){
		if(isset($_POST["uploadproject"])){
			if(!empty($_FILES["project"]["name"])){
				$filename = $_FILES["project"]["name"];
				$source = $_FILES["project"]["tmp_name"];
				$type = $_FILES["project"]["type"];
	
				$name = explode(".", $filename);
				$accepted_types = array('application/zip', 'application/x-zip-compressed', 'multipart/x-zip', 'application/x-compressed');
				$okay = false;
				foreach($accepted_types as $mime_type) {
					if($mime_type == $type) {
						$okay = true;
						break;
					} 
				}

				$continue = strtolower($name[1]) == 'zip' ? true : false;

				if($okay && $continue){
					$target_path = "../projects/".$this->link."/".$filename;  // change this to the correct site path
					if(move_uploaded_file($source, $target_path)) {
						$zip = new ZipArchive();
						$res = $zip->open($target_path);
						if ($res === true) {
							$zip->extractTo("../projects/".$this->link."/"); // change this to the correct site path
							$zip->close();
							unlink($target_path);
							$this->redirect("start", "A project feltöltése sikeres volt.");
						}
						else{
							$this->message = "Nem sikerült kicsomagolni a projektet!";
						}
					} else {	
						$this->message = "A projektet nem sikerült feltölteni a szerverre!";
					}
				}
				else{
					$this->message = "A megadott fájl nem .zip kiterjesztésű!";
				}	
			}
			else{
				$this->message = "Nem adta meg a fájlt!";
			}
		}
	}
}
?>
